import numpy as np
import open3d as o3d

class PointCloudAlgorithms:
    @staticmethod
    def denoise_statistical(point_cloud_data, k=20, std_ratio=2.0):
        """统计滤波去噪"""
        pcd = o3d.geometry.PointCloud()
        pcd.points = o3d.utility.Vector3dVector(point_cloud_data)
        _, ind = pcd.remove_statistical_outlier(nb_neighbors=k, std_ratio=std_ratio)
        return np.asarray(pcd.select_by_index(ind).points)

    @staticmethod
    def sample_down(point_cloud_data, voxel_size=0.01):
        """下采样（减少点数量）"""
        pcd = o3d.geometry.PointCloud()
        pcd.points = o3d.utility.Vector3dVector(point_cloud_data)
        downsampled = pcd.voxel_down_sample(voxel_size=voxel_size)
        return np.asarray(downsampled.points)

    @staticmethod
    def compute_metrics(gt_point_cloud, pred_point_cloud):
        """计算补全误差（CD误差）"""
        # 简化版CD误差计算（实际可使用PyTorch3D的官方实现）
        gt = gt_point_cloud / np.linalg.norm(gt_point_cloud, axis=1, keepdims=True)
        pred = pred_point_cloud / np.linalg.norm(pred_point_cloud, axis=1, keepdims=True)
        cd = np.mean(np.min(np.sqrt(np.sum((gt[:, None] - pred[None, :])**2, axis=-1)), axis=1))
        return {"cd_error": round(cd, 4)}